package bintree.heap.leetcode;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author haomin
 * @date 2022/03/23 22:40
 **/
public class Num692_topKFrequent2 {
    class Solution {
        public List<String> topKFrequent(String[] words, int k) {

            //建立一个顺序哈希表，按输入顺序存储
            LinkedHashMap<String,Integer> map = new LinkedHashMap<>();
            for(String word:words){
                map.put(word,map.getOrDefault(word,0)+1);
            }
            List<String> result = new ArrayList<>();

            //找k次最大值，值先result.add，然后map.remove
            for(int i=0;i<k;i++){
                int max = 0;
                String res="";
                for(String key: map.keySet()){
                    if(map.get(key)>max||(map.get(key)==max&&key.compareTo(res)<0)){
                        max = map.get(key);
                        res = key;
                    }
                }
                result.add(res);
                map.remove(res);
            }
            return result;
        }
    }
}